from pathlib import Path
from django.db.models import F
from django.http import JsonResponse
from django.shortcuts import render, get_object_or_404
from django.contrib.auth.decorators import login_required
from music.models import Genre, MusicDetail, MusicCollection, MusicClick
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from music.public_func import MusicRecommender


@login_required
def recommender(request):
    user_id = request.user.id
    print(user_id)
    recommender = MusicRecommender()
    recommended_music_ids = recommender.recommend_music_for(user_id, top_n=3)
    print(recommended_music_ids)
    music_objs = MusicDetail.objects.filter(id__in=recommended_music_ids)
    music_data_list = []
    for music_obj in music_objs:
        data_dict = {
            "id": music_obj.id,
            "name": music_obj.name,
            "pic_url": music_obj.pic_url,
            "lrc": "/files/lrc/" + Path(music_obj.lrc_path).name,
            "author": music_obj.author,
            "audio_path": "/files/audio/" + Path(music_obj.audio_path).name,
        }
        collection_obj = MusicCollection.objects.filter(user_id=user_id, music_id=music_obj.id).first()
        if collection_obj:
            data_dict["is_collection"] = True
        else:
            data_dict["is_collection"] = False
        print(music_obj.pic_url)
        music_data_list.append(data_dict)
    top_twenty_clicks = MusicClick.objects.all().order_by('-click_count')[:20]
    music_ids = [obj.music_id for obj in top_twenty_clicks]
    heat_music_list = []
    music_objs = MusicDetail.objects.filter(id__in=music_ids)
    for music_obj in music_objs:
        data_dict = {
            "id": music_obj.id,
            "name": music_obj.name,
            "pic_url": music_obj.pic_url,
            "lrc": "/files/lrc/" + Path(music_obj.lrc_path).name,
            "author": music_obj.author,
            "audio_path": "/files/audio/" + Path(music_obj.audio_path).name,
        }
        collection_obj = MusicCollection.objects.filter(user_id=user_id, music_id=music_obj.id).first()
        if collection_obj:
            data_dict["is_collection"] = True
        else:
            data_dict["is_collection"] = False
        heat_music_list.append(data_dict)
    return render(request, 'music/recommender.html', {"music_list": music_data_list, "heat_music_list": heat_music_list})


@login_required
def genre_view(request):
    # 获取当前用户加入的所有项目
    genre_objs = Genre.objects.all()
    genre_list = [{
        "title": genre_obj.name,
        "href": f"/music/music_list/?genre_id={genre_obj.id}"
    } for genre_obj in genre_objs]
    # 渲染页面，传递项目列表到模板
    return render(request, 'music/genre.html', {'genre_list': genre_list})


@login_required
def toggle_music_collection(request, music_id):
    user_id = request.user.id
    # 确保音乐存在
    music = get_object_or_404(MusicDetail, pk=music_id)

    # 尝试找到对应的收藏记录
    collection, created = MusicCollection.objects.get_or_create(
        user_id=user_id,
        music_id=music.id
    )

    if not created:
        collection.delete()
        return JsonResponse({'status': 'success', 'action': 'removed', 'message': '已取消收藏'})
    else:
        return JsonResponse({'status': 'success', 'action': 'added', 'message': '已添加收藏'})

@login_required
def music_click(request, music_id):
    user_id = request.user.id
    # 确保音乐存在
    music = get_object_or_404(MusicDetail, pk=music_id)

    music_click, created = MusicClick.objects.get_or_create(user_id=user_id, music_id=music.id)
    music_click.click_count = F('click_count') + 1
    music_click.save()
    return JsonResponse({'status': 'success', 'action': 'added', 'message': '已统计'})

@login_required
def music_list(request):
    genre_id = request.GET.get('genre_id', '')
    music_name = request.GET.get("music_name", '')
    is_collection = request.GET.get("is_collection", '')
    page_number = request.GET.get('page', 1)  # 获取URL中的页码参数，默认为第一页
    user_id = request.user.id
    # 执行查询
    if genre_id:
        music_objs = MusicDetail.objects.filter(genre_id=genre_id)
    elif music_name:
        music_objs = MusicDetail.objects.filter(
            name__icontains=music_name) | MusicDetail.objects.filter(
            author__icontains=music_name)
    elif is_collection:
        collection_objs = MusicCollection.objects.filter(user_id=user_id)
        music_ids = [collection_obj.music_id for collection_obj in collection_objs]
        music_objs = MusicDetail.objects.filter(id__in=music_ids)
    else:
        music_objs = MusicDetail.objects.all()  # 如果没有提供过滤条件，返回所有记录

    paginator = Paginator(music_objs, 10)
    try:
        music_page = paginator.page(page_number)
    except PageNotAnInteger:
        music_page = paginator.page(1)
    except EmptyPage:
        music_page = paginator.page(paginator.num_pages)

    # 构建音乐数据列表
    music_data_list = []
    for music_obj in music_page:
        data_dict = {
            "id": music_obj.id,
            "name": music_obj.name,
            "pic_url": music_obj.pic_url,
            "lrc": "/files/lrc/" + Path(music_obj.lrc_path).name,
            "author": music_obj.author,
            "audio_path": "/files/audio/" + Path(music_obj.audio_path).name,
        }
        collection_obj = MusicCollection.objects.filter(user_id=user_id, music_id=music_obj.id).first()
        if collection_obj:
            data_dict["is_collection"] = True
        else:
            data_dict["is_collection"] = False
        music_data_list.append(data_dict)
    return render(request, 'music/music_list.html',
                  {'genre_list': music_data_list, 'music_page': music_page, "genre_id": genre_id,
                   "music_name": music_name})